package com.shop.aop;

import com.shop.common.CustomException;
import com.shop.common.Result;
import com.shop.common.ResultCode;
import com.shop.common.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass().getName());

    /**
     * 拦截自定义异常
     * @ExceptionHandler 拦截指定的异常
     */
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Result notFount(CustomException e) {
        logger.error("业务异常：", e);
        return ResultGenerator.genFailResult(e.getMessage());
    }

    /**
     * 拦截未知的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result notFount(Exception e, HttpServletRequest request) {
        logger.error("未知的异常：", e);
        return ResultGenerator.genFailResult(ResultCode.INTERNAL_SERVER_ERROR, "未知的异常，请联系管理员");
    }

}
